#!/bin/sh
# misc functions

# $1 = device_name (ex: sda1, mmcblk0p1, sr0 - returns sda, mmcblk0, sr0)
fx_get_drvname() {
	case $1 in
		mmc*|nmve*) echo ${1%p*} ;; #remove trailing p*
		*) echo ${1:0:3} ;;         #assume sda, sr0, xxx
	esac
}

# $1 = bytes
fx_format_bytes() {
	[ $1 ] || return
	local BYTES=$1 FORMATTEDSIZE="${BYTES}B" # bytes
	if [ ${BYTES} -ge 1099511627776 ] ; then
		FORMATTEDSIZE="`dc $BYTES 1099511627776 \/ p`"
		FORMATTEDSIZE="`printf "%.2f" $FORMATTEDSIZE`T" #terabytes
	elif [ ${BYTES} -ge 1073741824 ] ; then
		FORMATTEDSIZE="`dc $BYTES 1073741824 \/ p`"
		FORMATTEDSIZE="`printf "%.1f" $FORMATTEDSIZE`G" # gigabytes
	elif [ ${BYTES} -ge 1048576 ] ; then
		FORMATTEDSIZE="$(( $BYTES / 1048576 ))M" # megabytes
	elif [ ${BYTES} -ge 1024 ] ; then
		FORMATTEDSIZE="$(( $BYTES / 1024 ))K" # kilobytes
	fi
	echo $FORMATTEDSIZE
}

# $1 = drv_name
fx_drv_is_optical() {
	[ $1 ] || return 1
	local xtype
	if [ -e /sys/block/${1}/device/type ] ; then
		read -r xtype < /sys/block/${1}/device/type
		[ "$xtype" = "5" ] && return 0
	fi
	if [ -e /proc/ide/${1}/media ] ; then
		read -r xtype < /proc/ide/${1}/media
		[ "$xtype" = "cdrom" ] && return 0
	fi
	return 1
}

# $1 = drv_name
fx_drv_is_usb() {
	[ $1 ] || return 1
	case $(readlink /sys/block/${1}) in *"/usb"[0-9]*)
		return 0 ;;
	esac
	return 1
}

#=====================================================

fx_personal_storage_free_mb() {
	[ $PUPMODE ] || . /etc/DISTRO_SPECS
	[ $SAVE_LAYER ] || . /etc/rc.d/PUPSTATE
	local F1 F2 F3 F4 F5plus SIZEFREEM
	case $PUPMODE in
		3|7|13|6|12|21|93)
			# PTN=" /initrd/mnt/dev_save" (savefolder)
			# PTN=" /initrd/pup_rw"       (savefile)
			#    -get mountpoint regardless of filetype-
			PTN=" $(stat -Lc %m /initrd/${SAVE_LAYER})" ;;
		*)
			PTN=" /" ;;
	esac
	while read F1 F2 F3 F4 F5plus ; do
		case "$F5plus" in *"$PTN")
			SIZEFREEM=${F4} ; break ;;
		esac
	done <<EOF
$(df -m)
EOF
	echo "$SIZEFREEM"
}

### END ###